﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using tjb.Utility.Config;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

namespace tjb.Utility.IConfig
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Formatter<T> where T : class
    {
        private IFormatter formatter = null;
        private XmlSerializer serializer = null;
        public Formatter()
        {
            serializer = new XmlSerializer(typeof(T));
        }
        public Formatter(FormatType type)
        {
            switch (type)
            {
                case FormatType.Binary:
                    formatter = new BinaryFormatter();
                    break;
                case FormatType.SoapXml:
                    formatter = new SoapFormatter();
                    break;
                case FormatType.Xml:
                    serializer = new XmlSerializer(typeof(T));
                    break;
                default:
                    throw new ArgumentException("不支持的格式化类型！");
            }
        }
        public T Deserialize(System.IO.Stream serializationStream)
        {
            if (serializer != null)
                return serializer.Deserialize(serializationStream) as T;
            else
                return formatter.Deserialize(serializationStream) as T;
        }

        public void Serialize(System.IO.Stream serializationStream, T graph)
        {
            if (serializer != null)
                serializer.Serialize(serializationStream, graph);
            else
                formatter.Serialize(serializationStream, graph);
        }


    }
}
